<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<?php
//require_once dirname(__FILE__).'/Authentication/AdminOnlyPageHeader.php';
$RootDirectoryUri = "http://localhost:8080/sql-pamokos";
require_once dirname(__FILE__).'/config/config.php';

?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>SQL mokomasis puslapis</title>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <link type="text/css" rel="stylesheet" media="all" href="css/styles.css" />
<!--    <link rel="stylesheet" type="text/css" media="screen" href="css/redmond/jquery.ui.theme.css" />a    -->
    <link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery.ui.theme.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" /> 


    <link rel="stylesheet" type="text/css" media="screen" href="css/AdminPageStyle.css" />

    <script src="scripts/modernizr-2.0.4.js"></script>
    <script src="scripts/jquery-1.7.1.min.js" type="text/javascript"></script> 
<!--    <script src="scripts/jquery.jqGrid.src.js" type="text/javascript"></script>     -->
    <script src="scripts/jquery.jqGrid.min.js" type="text/javascript"></script>
    <script src="scripts/grid.locale-lt.js" type="text/javascript"></script>
    <script src="scripts/grid.common.js" type="text/javascript"></script>
    <script src="scripts/grid.formedit.js" type="text/javascript"></script>
    <script src="scripts/jqDnR.js" type="text/javascript"></script>
    <script src="scripts/jqModal.js" type="text/javascript"></script>
</head>
<body>
    <div id="page-wrapper">
        <div id="page">
            <?php include(dirname(__FILE__).'/header1.php'); ?>
            <div class="content">
                <div class="left-side">
                    <?php include('menu-left.html'); ?>
                </div>
                <div class="right-side"> 
                    <h2>Užduočių redagavimas</h2>
                    <table id="list1"></table>
                    <div id="pager1"></div>

                    <!-- Duomenų redagavimo/įvedimo forma: SubForm -->
                    <form id="editForm" style="display:none;" action="/" data-mode="" >
                        <div class="SolidBorder form extended">
                          <table border="0">
                            <colgroup>
                                <col width="20%" />
                                <col width="30%" />
                                <col width="50%" />
                            </colgroup>
                            <thead>
                                <tr class="ui-jqdialog-title">
                                    <th colspan="2"><span id='FormTitle'>Naujas užrašas</span></th>
                                    <th>Lentelės</th>
                                </tr>
                            </thead>
                            <tbody> 
                                <tr>
                                    <td>Temos pavadinimas</td>
                                    <td class="padding">
                                        <textarea id="TaskDescription" rows="5" cols="24"></textarea>
                                    </td>
                                    <td rowspan="2">
                                        <select id="allTables" size="10" >
                                            <!-- Su PHP pagaminti lentelių sąrašą: option, option, ... lentelės vardas - lauke value -->
                                        	<?php 
                                        		$tbl = GetAllTables();
/*$myFile = "C:\\Gedimino\\temp2\\testFile6.txt";
$fh = fopen($myFile, 'w') or die("can't open file"); */       

                                                foreach ($tbl as $key => $value) {
/*
$str_ind = sprintf($key);
$str_tbl = sprintf($value);
$stringData = "$key={$key}; $value={$value}\n";
fwrite($fh, $stringData);
*/
                                                    echo "<option value='{$key}'>{$value}</option>\n";
                                                }
//fclose($fh);        
											?> 
                                        </select>
                                    </td>
                                </tr>
                                <tr>  
                                    <td>Komanda</td>
                                    <td class="padding">
                                        <textarea id="SqlDefinition" rows="5" cols="24"></textarea>
                                    </td>
                                </tr>
                                <tr>
                                    <td  colspan="2">
                                        <button type="button" class="DataEditButton" style="margin-left: 5px;"
                                                onClick= "return SubmitInsert(this);">Taip</button>
                                        <button type="button" class="DataEditButton" onClick= "return CancelInsert(this);">Ne</button>
                                    </td>
                                </tr>
                            </tbody>
                          </table>
                        </div>
                    </form>


                    <!-- Duomenu redagavimo/ivedimo forma: Forma -->
                    <form id="editForm1" style="display:none;" action="/" data-mode="" >
                        <div class="SolidBorder form">
                          <table border="0">
                            <colgroup>
                                <col width="50%" />
                                <col width="50%" />
                            </colgroup>
                            <thead>
                                <tr class="ui-jqdialog-title">
                                    <th colspan="2"><span id='FormTitle'>Temų redagavimas</span></th>
                                </tr>
                            </thead>
                            <tbody> 
                                <tr>
                                    <td>Temos pavadinimas</td>
                                    <td class="padding">
                                        <input id="Tema" type="text" name="Tema" style="width: 100%;" />
                                    </td>
                                </tr>
                               <tr>
                                    <td>
                                        <button type="button" class="DataEditButton" style="margin-left: 5px;"
                                                onClick= "return SubmitInsert_Temos(this);">Taip</button>
                                        <button type="button" class="DataEditButton" onClick= "return CancelInsert(this);">Ne</button>
                                    </td>
                                </tr>
                            </tbody>
                          </table>
                        </div>
                    </form>


                 </div>
            </div>
            <?php include('footer.html'); ?>
        </div>
    </div>
    <input type="hidden" id="hid" />

    <script type="text/javascript" src="scripts/navigacija.js"></script> 	
    <script type="text/javascript">
        $(document).ready(function(){
            var dataServerUrl = '<?php echo $RootDirectoryUri."/functions/PostNewTask.php?q=1"; ?>';
            jQuery("#list1").jqGrid({
                url: dataServerUrl,
                datatype: "xml",
                mtype: 'GET',
                colNames:['rcID','Užduoties Pavadinimas'],
                colModel:[
                    {name:'rcID',index:'rcID', width:20, align:"left", sortable:false, editable:false, search:false, hidden:true}, 
                    {name:'Pavadinimas',index:'Tema', width:150,align:"left", sortable:true, editable:false, 
                        search:true, edittype:'text', searchoptions: {sopt: ['eq','ne', 'bw','bn','in','ni','ew','en']}}
                    ],
                width: 800,
                height: 300,
                viewrecords: true,
                gridview: true,
                rowNum:10,
                rowList:[10,20,30],
                pager: '#pager1',
                sortname: 'rcID',
                sortorder: "ascending ",
                caption:"SQL pamokų užduotys",
                loadError: function(xhr, status, error) {
                    alert('Klaida: ' + status);
                },

                subGrid: true,
                subGridOptions: {
                    "plusicon"  : "ui-icon-triangle-1-e",
                    "minusicon" : "ui-icon-triangle-1-s",
                    "openicon"  : "ui-icon-arrowreturn-1-e"
                },                
                subGridRowExpanded: function(subgrid_id, row_id) {
                    var subgrid_table_id, pager_id;
                    var subgrid_table_id = subgrid_id + "_t";
                    var pager_id = "p_" + subgrid_table_id;
                    $("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table>" +
                                             "<div id='" + pager_id + "' class='scroll'></div>");
                    dataServerUrl = '<?php echo $RootDirectoryUri."/functions/PostNewTask.php?q=2&id="; ?>' + row_id;

                    jQuery("#"+subgrid_table_id).jqGrid({
                        url: dataServerUrl,
                        datatype: "xml",
                        mtype: 'GET',
                        colNames: ['rcID','Sąlyga','komanda','Duomenų lentelė'],
                        colModel: [
                            {name:"rcID",index:"rcID", width:20, sortable:false, editable:false, search:false, hidden:true}, 
                            {name:"Salyga",index:"salyga",width:130,
                                searchoptions: {sopt: ['eq','ne', 'bw','bn','in','ni','ew','en']}},
                            {name:"komanda",index:"komanda",width:130,align:"left",
                                searchoptions: {sopt: ['eq','ne', 'bw','bn','in','ni','ew','en']}},
                            {name:"table",index:"table",width:30,align:"right", search:false}
                        ],
                        width: 700,
                        rowNum:20,
                        pager: pager_id,
                        sortname: 'id',
                        sortorder: "asc",
                        height: '100%'
                    });

                    jQuery("#" + subgrid_table_id).jqGrid('navGrid', "#" + pager_id, {add:false, edit:false, del:false})
                        .navButtonAdd("#" + pager_id, {
                            caption: "",
                            title:"Naujas užrašas",
                            buttonicon:"ui-icon-plusthick",
                            onClickButton: function(){
                                ClearInputForm();
                                CreateNewRecord(subgrid_table_id, row_id);  
                               }, 
                            position:"last"
                        }).navButtonAdd("#" + pager_id, {
                            caption: "", 
                            title: "Taisyti užrašą",
                            buttonicon: "ui-icon-pencil",
                            onClickButton: function(){ 
                                $("#allTables option:selected").removeAttr("selected");
                                EditSelectedRecord(subgrid_table_id, row_id);  
                            },
                            position:"last"
                        }).navButtonAdd("#" + pager_id, {
                            caption: "", 
                            title: "Trinti užrašą",
                            buttonicon: "ui-icon-closethick",
                            onClickButton: function(){ 
                                $("#allTables option:selected").removeAttr("selected");
                                RemoveSelectedRecord(subgrid_table_id, row_id);
                                 
                            },
                            position:"last"
                        })
                }
            });
            jQuery("#list1").jqGrid('navGrid','#pager1',{add:false,edit:false,del:false})                   
                .navButtonAdd('#pager1', {
                    caption: "", 
                    title: "Užduočių temų redagavimas",
                    buttonicon: "ui-icon-pencil",
                    onClickButton: function(){ 
                       $('#editForm1').attr("data-mode", "edit");
                       $('#editForm1 span#FormTitle').text('Pataisykite užduoties temą')
                       FillDialog_Temos();
                       $('#editForm1').show();
                    },
                    position:"last"
			});                   
        });

        function FillDialog_Temos()
        {
            var myGrid = $('#list1')
            var selRowId = myGrid.jqGrid ('getGridParam', 'selrow');
            if (selRowId)
            {
                var selRow = myGrid.getRowData(selRowId);
                $('#editForm1').attr("data-id",selRow['rcID']);
                $('#editForm1 input#Tema').val(selRow['Pavadinimas']);
             }
            else
                alert("Pasirinkite koreguojamą eilutę paspausdami ją su pele.");
        }
		function SubmitInsert(activeButton) {
			var postData = CollectDetailData();
            if (ValidateDetailForm(postData))
            {
                $.ajax({
                    type: "POST",
                    url: "functions/PostnewTask.php?q=4",
                    data: postData,
                    cache: false,
                    success: function(data){
                        var answer = $.parseJSON(data);
                        var parameters = { 
                                rcID: answer.currentRecordId, Salyga: answer.taskDescription, komanda: answer.sqlDefinition, 
                                table: GetSelectedTableName(answer.selectedTable)
                            };
                        if (answer.operation == 'insert')
                           jQuery("#" + answer.tableId).jqGrid('addRowData', answer.currentRecordId, parameters, 'last');
                        else if (answer.operation == 'delete')
                           jQuery("#" + answer.tableId).jqGrid('delRowData', answer.currentRecordId);
                        else
                           jQuery("#" + answer.tableId).jqGrid('setRowData', answer.currentRecordId, parameters);
                    }
                }).fail(function(jqXHR, textStatus, errorThrown) { 
                    alert(errorThrown); 
                }).always(function() {
                    $('#editForm').hide();
                });
            }
            return false;
		}		
		
        function GetSelectedTableName(selectedTableId)
        {
            return $('form#editForm select#allTables option[value="' + selectedTableId + '"]').text();
        }

        function SubmitInsert_Temos(activeButton) {
			// Įterpia atnaujintus užrašus iš temų dialogo "Form1"
            var postData = CollectData();
            if (ValidateRootForm(postData))
            {
                $.ajax({
                    type: "POST",
                    url: "functions/PostnewTask.php?q=3",
                    data: postData,
                    cache: false,
                    success: function(data){
                        var json = $.parseJSON(data);
                        var parameters = { 
                                rcID: json.rcId, Pavadinimas: json.Tema
                            };
                        if (json.status == 'OK')
                        {
                            if (json.operation == 'insert')
                               jQuery("#list1").jqGrid('addRowData', json.rcId, parameters, 'last');
                            else if (json.operation == 'delete')
                               jQuery("#list1").jqGrid('delRowData', json.rcId);
                            else
                               jQuery("#list1").jqGrid('setRowData', json.rcId, parameters);
                        }
                        else
                            alert("Klaida: " + json.errorMessage);
                    }
                }).fail(function(jqXHR, textStatus, errorThrown) { 
                    alert(errorThrown); 
                }).always(function() {
                    $('#editForm1').hide();
                });
            }
            return false;
        }
        function ValidateRootForm(postData)
        {
            var rgx = new RegExp("^.*?(?=[\^#%&$\*:<>\?/\{\|\}]).*$");
            if(rgx.test(postData.Tema))
            {
/*                alert("Pašalinkite draudžiamus ženklus iš temos pavadinimo.");
                return false;
 */
            }
            return true;
        }
        function ValidateDetailForm(postData)
        {
            var rgx = new RegExp("^.*?(?=[\^#%&$\*:<>\?/\{\|\}]).*$");
            if(rgx.test(postData.taskDescription))
            {
/*
                alert("Pašalinkite draudžiamus ženklus iš temos pavadinimo.");
                return false;
            }
            if(rgx.test(postData.sqlDefinition))
            {
                alert("Pašalinkite draudžiamus ženklus iš komandos.");
                return false;
*/
            }
            return true;
        }

        function  ClearInputForm() {
            $('#editForm').removeAttr("data-mode");
            $('#editForm textarea').val('');
            $("#allTables option:selected").removeAttr("selected");
            $('#editForm textarea').removeAttr('readonly');
            $('#editForm select').removeAttr('disabled');
            
        }
        function CreateNewRecord(subgrid_table_id, row_id)
        {
           $('#editForm').attr("data-tableId", subgrid_table_id);
           $('#editForm').attr("data-mode", "insert");
           $('#editForm').attr("data-root-record", row_id);
           $('#editForm').attr("data-current-record", '0'); // Insertui šis parametras nereikalingas
           $('#editForm span#FormTitle').text('Užpildykite naują užrašą')
           $('#editForm').show();
        }
        function EditSelectedRecord(subgrid_table_id, row_id)
        {
            var selRow = FillDialog(subgrid_table_id);
            if (selRow)
            {
                $('#editForm').attr("data-tableId", subgrid_table_id);
                $('#editForm').attr("data-mode", "edit");
                $('#editForm').attr("data-root-record", row_id);
                $('#editForm').attr("data-current-record", selRow['rcID']);
                $('#editForm span#FormTitle').text('Pataisykite užrašo reikšmes');
                $('#editForm').show();   
            }
        }
        function RemoveSelectedRecord(subgrid_table_id, row_id)
        {
            var selRow = FillDialog(subgrid_table_id);
            if (selRow)
            {
                $('#editForm').attr("data-tableId", subgrid_table_id);
                $('#editForm').attr("data-mode", "delete");
                $('#editForm').attr("data-root-record", row_id);
                $('#editForm').attr("data-current-record", selRow['rcID']);
                $('#editForm span#FormTitle').text('Patvirtinkite užrašo trynimą');
                $('#editForm textarea').attr('readonly','readonly');
                $('#editForm select').attr('disabled','disabled');
                $('#editForm').show();   
            }
        }

        function FillDialog(subgrid_table_id)
        {
            var myGrid = $("#" + subgrid_table_id)
            var selRowId = myGrid.jqGrid ('getGridParam', 'selrow');
            if (selRowId)
            {
                var selRow = myGrid.getRowData(selRowId);

                $('#editForm textarea#TaskDescription').val(selRow['Salyga']);
                $('#editForm textarea#SqlDefinition').val(selRow['komanda']);
                var selectedTablename = selRow['table'];
                // Paselektinti lentelę liste, neradus tokios lentelės paselektinti pirmą
                $("#editForm select#allTables option").filter(function() {
                    return $(this).text() == selectedTablename; 
                }).attr('selected', 'selected');
                var count = $("#editForm select#allTables option[selected]").length;                
                if (count < 1)
                    $("#editForm select#allTables option:first").attr('selected','selected');
                return selRow;
            }
            else
            {
                alert("Pasirinkite koreguojamą eilutę paspausdami ją su pele.");
                return false;                
            }
        }
        function CancelInsert(activeButton) {
            $('#editForm1').hide(); // uždaro temos pop up langą
            $('#editForm').hide();	// uždaro užduočių pop Up langą
            return false;
        }
        function CollectData()
        {
			// užpildo temos atnaujinimo dialogą "Form1"
            var rzlt = { 
                mode: $('#editForm1').attr("data-mode"),
                rcId: $('#editForm1').attr("data-id"),      // Pataisyti į eilutės indeksą: GetRootRecordId
                Tema: $('#editForm1 table tbody tr td input#Tema').val(),
            };
            return rzlt;
        }
        function CollectDetailData()
        {
            var rzlt = {
                tableId: $('#editForm').attr("data-tableId"),
                mode: $('#editForm').attr("data-mode"),
                rootRecordId: GetRootRecordId($('#editForm').attr("data-root-record")),
                currentRecordId: $('#editForm').attr("data-current-record"),
                taskDescription: $('#editForm textarea#TaskDescription').val(),
                sqlDefinition: $('#editForm textarea#SqlDefinition').val(),
                selectedTable: $('#editForm select#allTables option:selected').val()
            };
            return rzlt;
        }
        function GetRootRecordId(recordIndex)
        {
            var rootRow = jQuery("#list1").jqGrid('getRowData', recordIndex);
            return rootRow['rcID'];
        }
    </script>
</body>
</html>